//
//  NewHomeViewController.swift
//  ManBetX
//
//  Created by Cocoa on 2020/4/27.
//  Copyright © 2020 Fullen. All rights reserved.
//

/**
 * 首页 Controller
 */
import UIKit

let verticalListCategoryViewHeight: CGFloat = 52 //悬浮categoryView的高度
let verticalListPinSectionIndex: Int = 0 //悬浮固定section的index
let homeHeadViewHeight = 558 + kNavigationBarHeight + verticalListCategoryViewHeight
let leftRightMargin: CGFloat = 0// 周边间距 - 8.0
let landscapeMargin: CGFloat = 0// 横向间距 - 14.0
let verticalMargin: CGFloat = 0// 竖向间距 - 16.0
let homeItemWidth: CGFloat = kScreenWidth/2
let homeItemHeight: CGFloat = 148.0

class HomeViewController: BaseViewController,JXCategoryViewDelegate,UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    @IBOutlet weak var collectionView: HomeListCollectionView!
    @IBOutlet weak var flowLayout:UICollectionViewFlowLayout!
    var homeHeadView: HomeHeadView?
    
    var navigationRightButton: UIButton?// 导航栏右侧按钮
    var currentOffsetY: CGFloat = 0// 当前scrollView 偏移量
    var setNavigationBarIsClear = true// 需要设置导航栏为透明
    var currentNavigationBarIsClear = true// 当前导航栏是否透明
    
    var bannerDataArray: NSMutableArray = NSMutableArray.init()// banner数据源
    var recommendGameInfoArray: NSMutableArray = NSMutableArray.init()// 推荐游戏数据
    var selectedRecommendGameTitle = ""// 当前选中推荐游戏的标题
    var selectGameDict: [String:Any]?// 当前选中推荐游戏的内容
    //全部游戏
    var allGameTitleArray: NSMutableArray = NSMutableArray.init()// 子控制器标题 - 全部游戏
    var allGameTitleAttributesArray: NSMutableArray = NSMutableArray.init()// 子控制器标题 - 全部游戏
    var allGameInfoArray: NSMutableArray = NSMutableArray.init()// 子控制器页面数据 - 全部游戏
    
    var pinCategoryView: JXCategoryTitleView = JXCategoryTitleView.init()
    
    // 点击推荐游戏需要
    var _effecView: UIView?
    var gameAlertView: GameAlertView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        configureUI()
        notificationCenterListener()
        
        configureJXCategory()
        configureDataSource()
        fetchPerformData()
        //检测版本更新
        fetchVersionUpdateInfo()
        
        self.collectionView.layoutSubviewsCallback = {
            
            self.updateSectionHeaderAttributes()
        }
        HomeSegmentCollectionCell.register(to: self.collectionView)
        self.collectionView.register(HomeHeadView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "HomeHeadViewId")
        
        self.collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "elementKindSectionHeaderId")
        self.collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "elementKindSectionFooterId")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //设置导航栏图片标题
        self.navigationItem.titleView = UIImageView.init(image: UIImage.init(named: "navi_icon_titleLogo"))
        
        self.navigationController?.navigationBar.shadowImage = UIImage()
        self.configureNavigationBarBackgroundImage()
        self.navigationRightButton?.isHidden = UserHelper.getLoginStatus()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        //重置导航栏背景
        self.navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
        self.navigationRightButton?.isHidden = true
    }
    
    deinit {
       NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: DefaultKey.USER_LOGIN_SUCCEED), object: nil)
       NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: DefaultKey.USER_LOGIN_OUT), object: nil)
    }
    
    // 检测版本更新
    func fetchVersionUpdateInfo() {
       
        AppDataConfigure.fetchAppchannel{ (dataDic) in
            let haveNewVersion = AppDataConfigure.isNeedUpdateVersion()
            // 检测是否需要强制更新
            if haveNewVersion == true {
                
                // 需要强制更新
                VersionUpdatePopViewController.showVersionUpdatePopViewController(caseType: .requireUpdate, updateBlock: {
                   self.requireUpdate()
                }) {}
            }else {
                // 检测是否需要显示新版本信息
                let isShowVersioninfo = AppDataConfigure.isNeedShowVersionInfo()
                if isShowVersioninfo == true {
                   self.showVersionInfo()
                }
            }
        }
    }
       
    // 点击 -- 强制更新
    func requireUpdate() {
        let dataDic: [String: Any] = GlobalInfo.appChannelDic!
        let fullVersionUrlString = dataDic["full_download_url"] as? String ?? ""
        if fullVersionUrlString.count > 0{
            DispatchQueue.main.async {
                let url = URL(string: fullVersionUrlString)
                if #available(iOS 10, *) {
                    UIApplication.shared.open(url!, options: [:],
                                                completionHandler: {
                                                (success) in
                    })
                } else {
                    UIApplication.shared.openURL(url!)
                }
            }
        }
    }
    // 展示新版本信息提示框
    func showVersionInfo() {
        let dataDic: [String: Any] = GlobalInfo.appChannelDic!
                             
        // 当前版本号
        let currentVersion = dataDic["current_version"] as? String ?? ""
        // 当前版本描述：如 最新版本
        let fullVersion = dataDic["status_name"] as? String ?? ""
        // 当前版本更细信息
        let notes = dataDic["notes"] as? String ?? ""
        // 注意：[++]  为字符串分隔符
        let notesArray = notes.components(separatedBy: "[++]") as NSArray
        let infoString = String.init(format: "%@：V%@", fullVersion,currentVersion)
        if notesArray.count > 0 {
            // 新版本信息弹框已经正常弹出，则记录
            UserDefaults.standard.set(true, forKey: DefaultKey.APP_SHOW_VERISON_INFO_YET)
            VersionInfoPopViewController.showVersionInfoPopViewController(infoString: infoString, dataArray: notesArray) {
                   print("close")
            }
        }
    }
    // MARK: -- FuncUI
    // 配置所有UI
    func configureUI() {
        self.view.backgroundColor = UIColor.init("F8F9FB")

        configureNavigationRightButton()
        configureBarButtonItem(isloginState: false)
        configureHeadView()
        self.configureCollectionRefresh()
    }
    // 配置refresh
    func configureCollectionRefresh() {
        self.collectionView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            ToolHelper.statisticsPage(pageName: "首页-首页-下拉刷新操作")
            self.refreshEvents()
        })
    }
    
    // 配置headView
    func configureHeadView() {
        // banner 点击
        self.homeHeadView?.homeBannerClickBlock = { [weak self] (data) in
            LoginViewController.loginIfNeedController(currentController: self!) {
                self!.topBannerClick(data: data)
            }
        }
         
        // 推荐游戏 点击
        self.homeHeadView?.homeRecommendButtonClickBlock = { [weak self] (index) in
            
            LoginViewController.loginIfNeedController(currentController: self!) {
                
                if index < self!.recommendGameInfoArray.count{
                    let viewModel = self!.recommendGameInfoArray.object(at: index) as? HomeSegmentViewModel
                    if viewModel != nil {
                        self!.selectGameDict = viewModel!.dataDic
                        self!.selectedRecommendGameTitle = viewModel!.gameTitle
                    }
                    self!.gameClick(dict: self!.selectGameDict)
                }else {
                    UIHelper.alertSimpleMessage(about: "暂无推荐游戏数据", withDescription: "", in: self!)
                }
            }
        }
    }
    
    func configureJXCategory() {
        
        self.pinCategoryView.backgroundColor = UIColor.white
        self.pinCategoryView.frame = CGRect.init(x: 0, y: 0, width: self.view.size.width, height: verticalListCategoryViewHeight)
        self.pinCategoryView.titles = (self.allGameTitleArray as! [String])
        self.pinCategoryView.titleColor = UIColor.init("6C6C6C")
        self.pinCategoryView.titleSelectedColor = UIColor.init("333333")
        self.pinCategoryView.titleFont = UIFont.init(name: "PingFangSC-Regular", size: 13)
        self.pinCategoryView.titleSelectedFont = UIFont.init(name: "PingFangSC-Medium", size: 16)
        
        let titleLineView = JXCategoryIndicatorLineView.init()
        titleLineView.verticalMargin = 10.0// 线的位置
        titleLineView.indicatorWidthIncrement = 12.0//线宽增量
        titleLineView.indicatorColor = UIColor.init("FFA855")
        titleLineView.scrollStyle = JXCategoryIndicatorScrollStyle.sameAsUserScroll
        self.pinCategoryView.indicators = [titleLineView];
        self.pinCategoryView.delegate = self
    }
    // 下拉刷新
    func refreshEvents() {
        self.configureDataSource()
        self.fetchPerformData()
    }
    
    // 滚动视图导航栏配置
    func changeNavigationBarBackgroundImage() {
        
        if self.setNavigationBarIsClear == true,self.currentNavigationBarIsClear == false {
            
            //设置导航栏背景透明
            self.navigationController?.navigationBar.setBackgroundImage(UIImage(),
                                                                        for: .default)
            self.currentNavigationBarIsClear = true
        }else if self.setNavigationBarIsClear == false,self.currentNavigationBarIsClear == true{
            self.navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
            self.currentNavigationBarIsClear = false
        }
    }
    
    // 页面出现导航栏配置
    func configureNavigationBarBackgroundImage(){
        if 15 < self.currentOffsetY {
            //设置导航栏默认
            self.navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
        }else if self.currentOffsetY <= 15  {
            //设置导航栏背景透明
            self.navigationController?.navigationBar.setBackgroundImage(UIImage(),
                                                                        for: .default)
        }
    }
    func notificationCenterListener() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(self.userLoginSucceed), name: NSNotification.Name(rawValue: DefaultKey.USER_LOGIN_SUCCEED), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(self.userLoginOut), name: NSNotification.Name(rawValue: DefaultKey.USER_LOGIN_OUT), object: nil)
    }
    
    // 配置 BarButtonItem
    func configureBarButtonItem(isloginState: Bool) {
        
        self.navigationRightButton?.isHidden = UserHelper.getLoginStatus()
        if UserHelper.getLoginStatus() {// 已登录
            self.navigationItem.leftBarButtonItem = nil
            self.navigationItem.rightBarButtonItem = nil
            
        }else {// 未登录
            self.navigationItem.leftBarButtonItem = nil
        }
    }
    // 配置顶部登录按钮
    func configureNavigationRightButton() {
        // 登录按钮
        self.navigationRightButton = UIButton.init(frame: CGRect(x: self.view.frame.width - 54, y: 0, width: 54, height: 28))
        // 渐变色
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = self.navigationRightButton!.bounds
        gradientLayer.colors = [
            UIColor.init("FBCE81")!.cgColor,
            UIColor.init("FF914A")!.cgColor
        ]
        gradientLayer.startPoint = CGPoint(x: 0, y: 0)
        gradientLayer.endPoint = CGPoint(x: 1, y: 0)
        self.navigationRightButton!.layer.insertSublayer(gradientLayer, at: 0)
        self.navigationRightButton!.clipRectCorner(direction: [UIRectCorner.topLeft,UIRectCorner.bottomLeft], cornerRadius: 14)
        self.navigationRightButton!.setTitle("  登录", for: UIControl.State.normal)
        self.navigationRightButton!.setTitleColor(UIColor.white, for: UIControl.State.normal)
        self.navigationRightButton!.titleLabel?.font = UIFont.systemFont(ofSize: 14.0)
        self.navigationRightButton!.addTarget(self, action: #selector(navigationRightButtonClick), for: UIControl.Event.touchUpInside)
        self.navigationController?.navigationBar.addSubview(self.navigationRightButton!)
        self.navigationRightButton!.snp.makeConstraints { (make) in
            make.centerY.right.equalToSuperview()
            make.width.equalTo(54)
            make.height.equalTo(28)
        }
    }

// MARK: -- Events
    // 顶部登录按钮点击
    @objc func navigationRightButtonClick() {
        LoginViewController.loginIfNeedController(currentController: self) {
            print("登录成功")
        }
    }
    @objc func userLoginSucceed() {
        DispatchQueue.main.async {
            self.navigationRightButton?.isHidden = true
        }
    }
    @objc func userLoginOut() {
        DispatchQueue.main.async {
            self.navigationRightButton?.isHidden = false
        }
    }
    
    func updateSectionHeaderAttributes(){
        
        //获取到所有的sectionHeaderAtrributes，用于后续的点击，滚动到指定contentOffset.y使用
        let attributes: NSMutableArray = NSMutableArray.init()
        var lastHeaderAttri: UICollectionViewLayoutAttributes?
        
        for index in 0..<self.allGameInfoArray.count {
            let attri = self.collectionView.collectionViewLayout.layoutAttributesForSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, at: NSIndexPath.init(item: 0, section: index) as IndexPath)
                       
            if (attri != nil) {
                attributes.add(attri as Any)
           }
           if index == self.allGameInfoArray.count - 1 {
               lastHeaderAttri = attri;
           }
        }
        if (attributes.count == 0) {
            return;
        }
        self.allGameTitleAttributesArray = attributes;
        
//        如果最后一个section条目太少了，会导致滚动最底部，但是却不能触发categoryView选中最后一个item。而且点击最后一个滚动的contentOffset.y也不好弄。所以添加contentInset，让最后一个section滚到最下面能显示完整个屏幕。
        let array = self.allGameInfoArray.lastObject as! NSArray
        let lastCellAttri = self.collectionView.collectionViewLayout.layoutAttributesForItem(at: NSIndexPath.init(item: array.count - 1, section: self.allGameInfoArray.count-1) as IndexPath)!
        
        let lastSectionHeight = lastCellAttri.frame.origin.y - (lastHeaderAttri?.frame.origin.y)!
        
        let value: CGFloat = self.view.bounds.size.height - homeHeadViewHeight - lastSectionHeight;
        if (value > 0) {
            self.collectionView.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: value, right: 0)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            if indexPath.section == verticalListPinSectionIndex {
                
                let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "HomeHeadViewId", for: indexPath)
                self.homeHeadView = headerView as? HomeHeadView
                self.homeHeadView?.configureRecommendGameData(self.recommendGameInfoArray)
                self.configureHeadView()
                //首次使用VerticalSectionCategoryHeaderView的时候，把pinCategoryView添加到它上面。
                if self.pinCategoryView.superview == nil {
                    
                    self.homeHeadView!.allGameCategoryView.addSubview(self.pinCategoryView)
                }
                return headerView
            }
            let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "elementKindSectionHeaderId", for: indexPath)
            header.backgroundColor = UIColor.white
            return header
        }
        let footer = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "elementKindSectionFooterId", for: indexPath)
        footer.backgroundColor = UIColor.clear
        return footer
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return self.allGameInfoArray.count
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let array = self.allGameInfoArray.object(at: section) as! NSArray
        return array.count
    }
       
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
       
        let collectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: HomeSegmentCollectionCell.getIdentifier(), for: indexPath) as! HomeSegmentCollectionCell
        
        let viewModel = self.getViewModelInAllGame(indexPath: indexPath)
        if viewModel != nil {
            collectionCell.configure(viewModel!)
        }
        return collectionCell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        LoginViewController.loginIfNeedController(currentController: self) {
            
            let viewModel = self.getViewModelInAllGame(indexPath: indexPath)

            if viewModel != nil {
                self.gameClick(dict: viewModel!.dataDic)
            }
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // 处理CategoryView
        if self.allGameTitleAttributesArray.count > 0 {
            let attri = self.allGameTitleAttributesArray.object(at: verticalListPinSectionIndex) as! UICollectionViewLayoutAttributes
            
            if scrollView.contentOffset.y >= (attri.frame.size.height - verticalListCategoryViewHeight - kNavigationBarHeight) {
                //当滚动的contentOffset.y大于了指定sectionHeader的y值，且还没有被添加到self.view上的时候，就需要切换superView
                if self.pinCategoryView.superview != self.view {
                    self.pinCategoryView.frame = CGRect.init(x: 0, y: kNavigationBarHeight, width: self.view.size.width, height: verticalListCategoryViewHeight)
                    self.view.addSubview(self.pinCategoryView)
                }
            }else if(self.pinCategoryView.superview != self.homeHeadView?.allGameCategoryView) {
                //当滚动的contentOffset.y小于了指定sectionHeader的y值，且还没有被添加到sectionCategoryHeaderView上的时候，就需要切换superView
                self.pinCategoryView.frame = CGRect.init(x: 0, y: 0, width: self.view.size.width, height: verticalListCategoryViewHeight)
                self.homeHeadView?.allGameCategoryView.addSubview(self.pinCategoryView)
            }
            
            if !(scrollView.isTracking || scrollView.isDecelerating) {
                //不是用户滚动的，比如setContentOffset等方法，引起的滚动不需要处理。
                return;
            }
            //用户滚动的才处理  homeHeadViewHeight = 558 + kNavigationBarHeight + verticalListCategoryViewHeight
            //获取categoryView下面一点的所有布局信息，用于知道，当前最上方是显示的哪个section
            let topRect = CGRect.init(x: 0, y: scrollView.contentOffset.y + verticalListCategoryViewHeight + kNavigationBarHeight + 1, width: self.view.bounds.size.width, height: 1)
            let topAttributes = self.collectionView.collectionViewLayout.layoutAttributesForElements(in: topRect)?.first
            
            let topSection = topAttributes?.indexPath.section
            
            if topAttributes != nil , topSection! >= verticalListPinSectionIndex {
                if self.pinCategoryView.selectedIndex != topSection! - verticalListPinSectionIndex {
                    //不相同才切换
                    self.pinCategoryView.selectItem(at: topSection! - verticalListPinSectionIndex)
                }
            }
        }
        
        // 处理导航栏
        self.currentOffsetY = scrollView.contentOffset.y
        if currentOffsetY > 15 {
            self.setNavigationBarIsClear = false
            self.changeNavigationBarBackgroundImage()
        }else if self.currentOffsetY <= 15  {
            self.setNavigationBarIsClear = true
            self.changeNavigationBarBackgroundImage()
        }
    }
    
    func getViewModelInAllGame(indexPath: IndexPath) ->HomeSegmentViewModel? {
        
        if indexPath.section < self.allGameInfoArray.count {
            let listArray = self.allGameInfoArray.object(at: indexPath.section) as? NSArray
            if listArray != nil,indexPath.row < listArray!.count {
                
                let viewModel = listArray?.object(at: indexPath.row) as! HomeSegmentViewModel
                return viewModel
            }
        }
        return nil
    }
    
//MARK: -- UICollectionViewDelegateFlowLayout
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        
        if section == verticalListPinSectionIndex {
            //categoryView所在的headerView要高一些
            return CGSize.init(width: self.view.bounds.size.width, height: homeHeadViewHeight)
        }
        return CGSize.init(width: self.view.bounds.size.width, height: 0.01)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize{
        if section == self.allGameInfoArray.count-1 {
            return CGSize.init(width: self.view.bounds.size.width, height: 20)
        }
        return CGSize.init(width: self.view.bounds.size.width, height: 0.01)
    }
   
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let viewModel = self.getViewModelInAllGame(indexPath: indexPath)
        
        if viewModel != nil {
            return viewModel!.cellSize()
        }
        return CGSize.init(width: homeItemWidth, height: homeItemHeight)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return landscapeMargin
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return verticalMargin
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {

        return UIEdgeInsets.init(top: leftRightMargin, left: leftRightMargin, bottom: leftRightMargin, right: leftRightMargin)
    }
    
//MARK: -- JXCategoryViewDelegate
    
    func categoryView(_ categoryView: JXCategoryBaseView!, didClickSelectedItemAt index: Int) {
        //这里关心点击选中的回调！！！
        let targetAttri = self.allGameTitleAttributesArray.object(at: index + verticalListPinSectionIndex) as! UICollectionViewLayoutAttributes
        
        if index == 0 {
            //选中了第一个，特殊处理一下，滚动到sectionHeaer的最上面
            self.collectionView.setContentOffset(CGPoint.init(x: 0, y: targetAttri.frame.origin.y + homeHeadViewHeight - verticalListCategoryViewHeight - kNavigationBarHeight), animated: true)
        }else {
            self.collectionView.setContentOffset(CGPoint.init(x: 0, y: targetAttri.frame.origin.y - kNavigationBarHeight - verticalListCategoryViewHeight ), animated: true)
        }
    }
    
    // MARK: -- FuncDataSource
    func configureDataSource(){
        // 接口返回 banner 数据
        getBannerDataSource()
        
        // 配置 推荐游戏数据
        self.recommendGameInfoArray = HomeDataProvider.fetchRecommendGameData()
        // 配置 segment 全部游戏数据
        self.allGameTitleArray = HomeDataProvider.fetchAllGameTitleData()
        // 配置 segment 全部游戏标题
        self.allGameInfoArray = HomeDataProvider.fetchAllGameData()
        
        self.collectionView.reloadData()
        
        self.pinCategoryView.titles = (self.allGameTitleArray as! [String])
        self.pinCategoryView.reloadData()
    }
    
    //处理banner广告图携带id
    func getBannerDataSource(){
        let memberInfoData  = GlobalInfo.memberInfoData
        self.bannerDataArray.removeAllObjects()
        if memberInfoData != nil {
            let imageUrls = memberInfoData?["banner3"] as? [[String:Any]] ?? []
            if imageUrls.count > 0 {
               self.bannerDataArray.addObjects(from: imageUrls)
                self.homeHeadView?.configureDataSource(self.bannerDataArray)
            }
        }
    }

    //刷新页面数据
    func fetchPerformData(){
        NetWorkRequest(API.memberInfoUL(url: "face82b", ccToken: API.getCcToken(), vcToken: API.getVcToken()), completion:  { (responseData,statusCode,strData) -> (Void) in
            if(statusCode == 200){
                //取出data的数据并转化为字典数据
                let dataDict = responseData["data"].dictionaryObject
                //获取到状态值
                let statusStringJson = responseData["status"]
                //把状态值的字符串转为int值
                let statusString = Int("\(statusStringJson)")
                //获取到传递过来的msg
                let msgStringJson = responseData["msg"]
                //把msgStringJson转为字符串
                let msgString = "\(msgStringJson)"
                //判断是否相等的
                DispatchQueue.main.async{
                    if(statusString == 0){
                        let memberInfoDic = dataDict?["response"] as? [String:Any] ?? [:]
                        GlobalInfo.memberInfoData = memberInfoDic
                        
                        self.getBannerDataSource()
                        self.collectionView.reloadData()
                        
                        if memberInfoDic["playerid"] != nil {
                            self.fetchHallInfo()
                        }
                    }else{
                        //弹出报错后的问题
                        UIHelper.alertSimpleMessage(about: msgString, withDescription: "", in: self)
                        
                        self.collectionView.mj_header?.endRefreshing()
                    }
                }
            }else{
                DispatchQueue.main.async {
                    //弹出报错后的问题
                    UIHelper.alertSimpleMessage(about: "获取用户信息失败!", withDescription: "", in: self)
                    self.collectionView.mj_header?.endRefreshing()
                }
            }
        },failed: {(faildInfo,reCode,msg) -> (Void) in
            DispatchQueue.main.async {
                if reCode == "21002"{
                       UIHelper.displayLoginExpireTip(self)
                }else{
                    UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
                }
                self.collectionView.mj_header?.endRefreshing()
            }
        }){() -> (Void) in
            DispatchQueue.main.async {
                UIHelper.alertSimpleMessage(about: "网络请求异常!", withDescription: "", in: self)
                self.collectionView.mj_header?.endRefreshing()
            }
        }
    }
    // 处理游戏大厅信息
    func fetchHallInfo() {
        HomeDataProvider.fetchHallInfo(succeed: {
            DispatchQueue.global().async {
                // 配置游戏状态 - 维护中？ -- 推荐游戏
                for viewModel in self.recommendGameInfoArray {
                    if viewModel is HomeSegmentViewModel {
                        let tempVM = viewModel as! HomeSegmentViewModel
                        tempVM.isUnderMaintenance = self.getGameMaintenanceStatus(gameId: tempVM.gameId)
                    }
                }
                // 配置游戏状态 - 维护中？ -- 全部游戏
                for listArray in self.allGameInfoArray where listArray is NSArray {
                    
                    for viewModel in (listArray as! NSArray){
                        if viewModel is HomeSegmentViewModel {
                            let tempVM = viewModel as! HomeSegmentViewModel
                            tempVM.isUnderMaintenance = self.getGameMaintenanceStatus(gameId: tempVM.gameId)
                        }
                    }
                }
                DispatchQueue.main.async{
                    self.collectionView.reloadData()
                    self.collectionView.mj_header?.endRefreshing()
                }
            }
        }) {
            // 提示
            DispatchQueue.main.async {
                UIHelper.alertSimpleMessage(about: "刷新失败", withDescription: "获取游戏大厅信息有误，请联系客服处理", in: self)
                self.collectionView.mj_header?.endRefreshing()
            }
        }
    }
    // 根据游戏Id和大厅信息，匹配改是否在维护中
    func getGameMaintenanceStatus(gameId: String) -> Bool {
        
        if let hallInfoData = GlobalInfo.hallInfoData {
            
            for hallDict in hallInfoData{
                let hallGameId = hallDict["id"] as? String ?? "0"
                if hallGameId == gameId {
                  let status = hallDict["status"] as? Int ?? -1
                    if status == 0{
                        return true
                    }
                    return false
                }
            }
        }
        return false
    }

    //banner图
    func topBannerClick(data:[String:Any]) -> Void {
        //跳转优惠列表
        ToolHelper.statisticsPage(pageName: "首页-轮播图-轮播图")
        let type = data["type"] as? Int ?? 0
        switch type {
        case 1:
             let bannerId = data["action"] as? String ?? "-1"
            self.showLoadHUD(title: "读取中")
            RequestHelper.get(atPath: "/clientsAPIs/myactivity", withCompletion: { data in
                if let activityInfoArray = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]]{
                    DispatchQueue.main.async {
                        var isPushList = true
                        //1.从bannerids根据index获取到id
                        //2.从activityInfoArrays中找出actid相同的
                        //3.把dict取出来传递,dict ,及位于数组中的下标
                        for (index,item) in activityInfoArray.enumerated(){
                            let actid = item["actid"] as? String ?? ""
                            if bannerId == actid{
                                
                                let goNext = TabMineActivityDetailViewController.instanceFromStoryboard()!
                                goNext.activity = item
                                goNext.activityImage = imageNamed("img_default_banner")
                                goNext.activityImageHeight = 65
                                //实现闭包,获取到传递的参数
                                goNext.listIndex = index
                                goNext.hidesBottomBarWhenPushed = true
                                self.navigationController?.pushViewController(goNext, animated: true)
                                isPushList = false
                                break
                            }
                        }
                        if isPushList == true{
                            let vc = PromotionsVC()
                            vc.dataArray = activityInfoArray
                            vc.hidesBottomBarWhenPushed=true
                            self.navigationController?.pushViewController(vc, animated: true)
                        }
                        self.dismissLoadHUD()
                    }
                }
            }, withError: { error in
                DispatchQueue.main.async {
                    self.dismissLoadHUD()
                    UIHelper.alertSimpleMessage(about: "读取失败", withDescription: "未成功读取活动信息，请稍后重试，\(getErrorString())", in: self)
                }
            })
            break
        case 2:
            if var ios = data["ios"] as? String{
                if(ios == ""){
                    DispatchQueue.main.async {
                    UIHelper.alertSimpleMessage(about: "未配置页面路径", withDescription: "")
                    }
                    return
                }
                guard  let nameSpace = Bundle.main.infoDictionary!["CFBundleExecutable"] as? String else {
                    return
                }
                
                let iosType = data["iosType"] as? String ?? ""
                if(iosType == "xib"){
                    if ios == "registerViewController" {//跳转至注册页
                        ios = "RegisterViewController"
                    }
                    
                    guard let classfullName = NSClassFromString(nameSpace + "." + ios) else {
                        return
                    }
                    guard let childVC = classfullName as? UIViewController.Type else {
                        return
                    }
                    
                    let goNext = childVC.instanceFromStoryboard()
                    if goNext != nil {
                        self.navigationController?.pushViewController(goNext!, animated: true)
                        return
                    }
                }
                // 点击的时候判断登录就好了 - 下面代码是否可以不要
//                if(ios.contains("Login")){
//                    let vc = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "loginNavigationViewController") as? LoginNavigationViewController
//                    UIApplication.shared.keyWindow?.rootViewController = vc
//                    return
//                }
                
                /*
                       此句代码没有进行解包，只是判断可选类型是否为nil
                       */
//                      guard  let nameSpace = Bundle.main.infoDictionary!["CFBundleExecutable"] as? String else {
//                          return
//                      }
                      
                      ///2:获取类名
                      
                      /*
                       1:获取的类名，classfullName的类型为AnyClass?类型
                       
                         let classfullName = NSClassFromString(nameSpace! + "." + className)
                       2:直接用guard else进行校验，当用 let classfullName = NSClassFromString(nameSpace! + "." + className)此种类型为可选绑定，有值的话，直接将可选类型进行解包
                       3：如果 guard (nameSpace != nil) else {
                           return
                       }
                       此种写法，不会对nameSpace进行解包
                      
                       */
                      ///3:创建对象
                guard let classfullName = NSClassFromString(nameSpace + "." + ios) else {
                    return
                }
                guard let childVC = classfullName as? UIViewController.Type else {
                    return
                }
                let vc = childVC.init()
                vc.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(vc, animated: true)
                
            }else{
                DispatchQueue.main.async {
                UIHelper.alertSimpleMessage(about: "未配置页面路径", withDescription: "")
                }
            }
            break
        case 3:
            let url = data["action"] as? String ?? ""
            if(url != ""){
                if(url.hasPrefix("http")){
                    let goNext: WebViewController = WebViewController.init()
                    goNext.url = url
                    goNext.hidesBottomBarWhenPushed = true
                     self.navigationController?.pushViewController(goNext, animated: true)
                }else{
                    let uri = URL(string: url)
                    if #available(iOS 10, *) {
                        UIApplication.shared.open(uri!, options: [:],
                                                  completionHandler: {
                                                    (success) in
                        })
                    } else {
                        UIApplication.shared.openURL(uri!)
                    }
                }
            }else{
                DispatchQueue.main.async {
                   UIHelper.alertSimpleMessage(about: "未配置url路径", withDescription: "")
                }
            }
            
            break
        case 4:
            let url = data["action"] as? String ?? ""
            if(url != ""){
                let uri = URL(string: url )
                if #available(iOS 10, *) {
                    UIApplication.shared.open(uri!, options: [:],
                                             completionHandler: {
                                               (success) in
                    })
                } else {
                    UIApplication.shared.openURL(uri!)
                }
            }else{
                DispatchQueue.main.async {
                    UIHelper.alertSimpleMessage(about: "未配置url路径", withDescription: "")
                }
            }
            break
        default:
            break
        }
    }
    
    //MARK:-- 以下为进入游戏方法需要
        
    //游戏跳转
    func gameClick(dict:[String:Any]?){
        if dict?["gpid"] as! String == "1"{
            let alertCon = UIAlertController.init(title:"输入地址", message:nil, preferredStyle:.alert)
            let confirmAction = UIAlertAction.init(title:"确定", style:UIAlertAction.Style.default, handler: { (a) in
                let textField = alertCon.textFields?.first
                // 点击确定后页面对于输入框内容的处理逻辑
                // print("测试\(textField?.text)")
                UserDefaults.standard.set(textField?.text ?? "", forKey: DefaultKey.TEST_URL)
                
                self.toTestPage(url: textField?.text ?? "", gpid: dict?["gpid"] as? String ?? "",usWK:dict?["use_WK"] as? Bool ?? false)
                
            })
            alertCon.addAction(confirmAction)
            alertCon.addAction(UIAlertAction.init(title:"取消", style:.cancel, handler:nil))
            alertCon.addTextField(configurationHandler: { (textField) in
                textField.placeholder = "填写测试地址"
                let testUrl = UserDefaults.standard.string(forKey: DefaultKey.TEST_URL)
                if testUrl != nil{
                    textField.text = testUrl
                }
            })
            self.present(alertCon, animated:true, completion:nil)
            return
        }
        if let name = getHall(withId: dict!["id"] as? String){
            let flag : Int = name["flag"] as! Int
            if(flag != 1){
                let s = name["s"] as? String ?? ""
                let e = name["e"] as? String ?? ""
                let tip = "系统维护中（\(s)  -  \(e)\n暂时无法进入游戏）"
                UIHelper.alertSimpleMessage(about: tip, withDescription: "", in: self)
                return
            }
        }
//         print("游戏==========>：\(dict)")
        if PlatformApp.getInstance(dict!["gpid"] as! String) != nil{
            let isRedirect = dict?["iredirect_to_app"] as? Bool ?? false
            if isRedirect == false{
                let isapp = dict?["isapp"] as? Bool ?? false
                let name = dict?["name"] as? String ?? ""
                if(name.contains("万博体育")){
                    let dialogMessage = UIAlertController(title: "娱乐提示", message: "请选择打开方式", preferredStyle: .alert)
                    dialogMessage.view.tintColor = UIColor.black
                    let ok = UIAlertAction(title: "APP", style: .default, handler: { (action) -> Void in
                        //跳转体育app
                        self.ationWithApp()
                    })
                    
                    let cancelExit = UIAlertAction(title: "WAP", style: .default, handler: { (action) -> Void in
                        if UserHelper.getLoginStatus() {
                            self.continueWithGamePlatform(platform: dict)
                        }else {
                            LoginViewController.loginIfNeedController(currentController: self) {}
                        }
                    })
                    
                    dialogMessage.addAction(ok)
                    dialogMessage.addAction(cancelExit)
                    
                    self.tabBarController?.present(dialogMessage, animated: true, completion: nil)
                }else{
                    if isapp != true{
                        if UserHelper.getLoginStatus() {
                            self.continueWithGamePlatform(platform: dict)
                        }else {
                            LoginViewController.loginIfNeedController(currentController: self) {}
                        }
                    }else{
                        //跳转体育app
                        self.ationWithApp()
                    }
                }
                
            }else{
                let alertTitle  = dict?["name"] as? String ?? ""
                self._effecView = UIHelper.showBlurEffect(isClick:true)
                self.parent?.parent?.view.addSubview(self._effecView!)
                let alert = GameAlertView.init(title: "\(alertTitle)提示")
                self.gameAlertView = alert
                alert.closeBtn?.addTarget(self, action: #selector(ationWithClose), for: .touchUpInside)
                alert.htmlBtn?.addTarget(self, action: #selector(ationWithHTML), for:.touchUpInside)
                alert.html5Btn?.addTarget(self, action: #selector(ationWithHTML), for:.touchUpInside)
                alert.appBtn?.addTarget(self, action: #selector(ationWithApp), for:.touchUpInside)
                alert.appsBtn?.addTarget(self, action: #selector(ationWithApp), for:.touchUpInside)
                alert.show(target: self, animated: true)
            }
        }else{
            let isapp = dict?["isapp"] as? Bool ?? false
            if isapp == true { //跳转体育app
                self.ationWithApp()
            }else{
                if UserHelper.getLoginStatus() {
                    self.continueWithGamePlatform(platform: dict)
                }else {
                    LoginViewController.loginIfNeedController(currentController: self) {}
                }
            }
            
        }
    }
    
    func toTestPage(url:String,gpid:String,usWK:Bool) -> Void {
        if usWK == false{
            let goNext: GameWebViewController = GameWebViewController.instanceFromStoryboard()!
                
            goNext.gpid = gpid
            goNext.url = url
            goNext.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(goNext, animated: true)
        }else{
            let goNext = GameWKWebViewController.instanceFromStoryboard()!
                
            goNext.gpid = gpid
            goNext.url = url
            goNext.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(goNext, animated: true)
        }
    }
    
    func getHall(withId: String?) -> [String:Any]? {
        if let hallInfoData = GlobalInfo.hallInfoData {
            for hall in hallInfoData {
                let id = hall["id"] as? String ?? "0"
                if id == withId {
                    return hall
                }
            }
        }
        return nil
    }
    
    @objc func ationWithApp(){
        self._effecView?.removeFromSuperview()
        self.gameAlertView?.dismiss(animated: true)
        func callback(_ app: PlatformAppProtocol) {
            if UIApplication.shared.canOpenURL(app.url!){
                self.dismissLoadHUD()
                let isOpen = UIApplication.shared.openURL(app.url!)
                if isOpen == false{
                    UIHelper.alertSimpleMessage(about: "请检查体育APP是否添加信任描述文件.", withDescription: "")
                }
            } else {
                if let gameInfoData = GlobalInfo.gameInfoData {
                    if let downloadInfo = gameInfoData[app.downloadParam] as? [String: Any]{
                        if let iosDLString = downloadInfo["ios"] as? String {
                            let clientMessage = app.name.uppercased() + " 客户端"
                            let dialogMessage = UIAlertController(title: "娱乐提示", message: "是否下载 \(clientMessage)", preferredStyle: .alert)
                            dialogMessage.view.tintColor = UIColor.black
                            let ok = UIAlertAction(title: "前往下载", style: .default, handler: { (action) -> Void in
                                if let url = URL(string: iosDLString) {
                                    UIApplication.shared.openURL(url)
                                }else{
                                    DispatchQueue.main.async {
                                        UIHelper.alertSimpleMessage(about: "无法前往下载链接", withDescription: "")
                                    }
                                }
                            })
                            
                            let cancelEnter = UIAlertAction(title: "忽略，直接进入游戏", style: .default, handler: { (action) -> Void in
                                self.toGamePage(dict: self.selectGameDict) //进入h5
                            })
                            let cancelExit = UIAlertAction(title: "取消", style: .default, handler: { (action) -> Void in
                            })
                            dialogMessage.addAction(ok)
                            dialogMessage.addAction(cancelExit)
                            
                            self.tabBarController?.present(dialogMessage, animated: true, completion: nil)
                        } else {
                            DispatchQueue.main.async {
                            }
                            UIHelper.alertSimpleMessage(about: "无法取得下载链接", withDescription: "")
                        }
                    } else {
                        UIHelper.alertSimpleMessage(about: "无法取得下载链接", withDescription: "")
                    }
                }
                self.dismissLoadHUD()
            }
        }
        
        self.dismissLoadHUD()
        let gpid = self.selectGameDict?["gpid"] as! String
        if let app = PlatformApp.getInstance(gpid){
            app.routeGame(callback)
        }else{
            self.toGamePage(dict: self.selectGameDict)
        }
    }
    
    //2.0进入游戏平台
    func continueWithGamePlatform(platform:[String:Any]?){
        let isMaintain = platform?["status"] as? Int ?? 0
        
        if UserHelper.getLoginStatus() {
            //mt
            self._effecView?.removeFromSuperview()
            self.gameAlertView?.dismiss(animated: true)
            if isMaintain == 0 {
                UIHelper.alertSimpleMessage(about: "此游戏平台正在维护", withDescription: "", in: self)
                return
            }
            self._effecView=UIHelper.showBlurEffect(isClick:false)
            self.parent?.parent?.view.addSubview(self._effecView!)
            self._loadView = UIHelper.initLoadView(self, withMessage: "进入游戏中...")
            self.parent?.parent?.view.addSubview(self._loadView!)
            
            NetWorkRequest(API.goInGamePlatform(url: "04976c8", gpid: platform!["gpid"] as? String ?? ""), completion: { (responseData,statusCode,strData) -> (Void) in
                DispatchQueue.main.async {
                    self._loadView?.removeFromSuperview()
                    self._effecView?.removeFromSuperview()
                    let dataDict = responseData["data"].dictionary
                    let onekeyriResponse = dataDict?["onekeyriResponse"]?.dictionary
                    let enterGameResponse = dataDict?["enterGameResponse"]?.dictionary
                    let oresponse = onekeyriResponse?["response"]?.dictionary
                    let code = oresponse?["c"]?.int  ?? -1
                    if code == 0 {
                        //  self.toGamePage(dict: platform)
                        let ecode =  enterGameResponse?["code"]?.int ?? -1
                        if ecode == 0{
                            ToolHelper.statisticsPage(pageName:"\(self.selectedRecommendGameTitle)-\(platform?["name"] as? String ?? "")-api_成功")
                            let data = enterGameResponse?["data"]?.array
                            if data?.count ?? 0 <= 0 {
                                UIHelper.alertSimpleMessage(about: "数据异常。", withDescription: "", in: self)
                                return
                            }
                            //获取数组第一个的数据
                            let s = data?[0].dictionaryObject
                            if s?["status"] as? Int ?? -1 == 1 {
                                let gp = data?[1].dictionaryObject
                                if gp?["status"] as? Int ?? -1 == 1 {
                                    if gp?["c"] as? Int ?? -1 == 1  || gp?["c"] as? Int ?? -1 == 0{
                                        if data?.count ?? 0 > 2{
                                            let dict = data?[2].dictionaryObject
                                            if let str = (dict?["data"] as? [String:Any])?["val"] {
                                                var zeroFlag: Bool = false
                                                if str is String {
                                                    zeroFlag = ((str as? String) == "0.00")
                                                }else {
                                                    zeroFlag = ((str as? Int) == 0)
                                                }
                                                //进入游戏
                                                self.pushGameViewController(platform!)
                                                //                                                }
                                            }else{
                                                UIHelper.alertSimpleMessage(about: "检查账户失败，请稍后重试。", withDescription: "", in: self)
                                            }
                                        }else{
                                            //进入游戏
                                            self.pushGameViewController(platform!)
                                        }
                                    }else{
                                        //注册游戏
                                        print("注册游戏")
                                        UIHelper.alertSimpleMessage(about: "注册游戏失败，请稍后重试。", withDescription: "", in: self)
                                        //    self.checkReg(platform!)
                                    }
                                }else{
                                    UIHelper.alertSimpleMessage(about: "系统维护中，当前无法进入游戏，在此期间建议您选择其它万博游戏平台娱乐", withDescription: "", in: self)
                                }
                            }else{
                                let tip: String = "系统维护中(\(s?["s"] as? String ?? "")-\(s?["e"] as? String ?? ""))，当前无法进入游戏"
                                UIHelper.alertSimpleMessage(about: tip, withDescription: "", in: self)
                            }
                        }else if code == 999 || code == 1150 {
                            //mt 20171221
                            UIHelper.removeEffect()
                            LoginViewController.loginIfNeedController(currentController: self) {}
                            ToolHelper.statisticsPage(pageName:"\(self.selectedRecommendGameTitle)-\(platform?["name"] as? String ?? "")-api_失败")
                        }else{
                            ToolHelper.statisticsPage(pageName:"\(self.selectedRecommendGameTitle)-\(platform?["name"] as? String ?? "")-api_失败")
                             UIHelper.alertSimpleMessage(about: "发生错误: \(Int(code)) \(CodeMessageHelper.get(String(code)))", withDescription: "", in: self)
                        }
                    }else if code == 999 || code == 1150 {
                        //mt 20171221
                        UIHelper.removeEffect()
                        LoginViewController.loginIfNeedController(currentController: self) {}
                        ToolHelper.statisticsPage(pageName:"\(self.selectedRecommendGameTitle)-\(platform?["name"] as? String ?? "")-api_失败")
                    }else{
                        ToolHelper.statisticsPage(pageName:"\(self.selectedRecommendGameTitle)-\(platform?["name"] as? String ?? "")-api_失败")
                        UIHelper.alertSimpleMessage(about: "发生错误: \(Int(code)) \(CodeMessageHelper.get(String(code)))", withDescription: "", in: self)
                    }
                }
            }, failed: { (faildInfo,reCode,msg) -> (Void) in
                DispatchQueue.main.async {
                    ToolHelper.statisticsPage(pageName:"\(self.selectedRecommendGameTitle)-\(platform?["name"] as? String ?? "")-api_失败")
                    if reCode == "21002"{
                        LoginViewController.loginIfNeedController(currentController: self) {}
                    }else{
                       UIHelper.alertSimpleMessage(about: "发生错误: \(Int(reCode)) \(msg))", withDescription: "", in: self)
                    }
                    
                    self._loadView?.removeFromSuperview()
                    self._effecView?.removeFromSuperview()
                }
            }) { () -> (Void) in
                DispatchQueue.main.async {
                    ToolHelper.statisticsPage(pageName:"\(self.selectedRecommendGameTitle)-\(platform?["name"] as? String ?? "")-api_失败")
                    UIHelper.alertSimpleMessage(about: "发生错误，请联系客服协助处理，\(getErrorString())", withDescription: "", in: self)
                    //mt 20171221
                    self._loadView?.removeFromSuperview()
                    self._effecView?.removeFromSuperview()
                }
            }
        }else{
            self.gameAlertView?.didTappedOnBackgroundView()
            LoginViewController.loginIfNeedController(currentController: self) {}
        }
    }
    @objc func ationWithClose(){
        self.gameAlertView?.didTappedOnBackgroundView()
    }
    @objc func ationWithHTML(){
        self.continueWithGamePlatform(platform: self.selectGameDict)
    }
    
    //进入游戏
    func toGamePage(dict:[String:Any]?){
        let gpid = dict?["gpid"] as? String
        let accid = dict?["accid"] as? String
        DispatchQueue.main.async {
            self.dismissLoadHUD()
            self._loadView = UIHelper.initLoadView(self, withMessage: "检查账户...")
            self.parent?.parent?.view.addSubview(self._loadView!)
        }
        
        print("参数/kz/gp/v1/enter?id=\(gpid!) accid:\(accid!)")
        RequestHelper.post(atPath:"/kz/gp/v1/enter?id="+gpid!, withData: ["accid":accid!], withCompletion: { data in
            let responseObject = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] ?? [:]
            let code = responseObject["code"] as? Int ?? -1
            DispatchQueue.main.async{
                if data.count <= 0{
                    ToolHelper.statisticsPage(pageName:"\(self.selectedRecommendGameTitle)-\(dict?["name"] as? String ?? "")-api_失败")
                    UIHelper.alertSimpleMessage(about: "接口数据异常。", withDescription: "", in: self)
                    self._effecView?.removeFromSuperview()
                    self._loadView?.removeFromSuperview()
                    return
                }
                if code == 0 {
                    ToolHelper.statisticsPage(pageName:"\(self.selectedRecommendGameTitle)-\(dict?["name"] as? String ?? "")-api_成功")
                    let data = responseObject["data"] as? [[String:Any]]  ?? []
                    print("Check Enter:\(responseObject)")
                    if data.count <= 0 {
                        self.dismissLoadHUD()
                        self._effecView?.removeFromSuperview()
                        UIHelper.alertSimpleMessage(about: "数据异常。", withDescription: "", in: self)
                        return
                    }
                    let s = data[0]
                    if s["status"] as? Int ?? -1 == 1 {
                        let gp = data[1]
                        if gp["status"] as? Int ?? -1 == 1 {
                            if gp["c"] as? Int ?? -1 == 1 {
                                //进入游戏 上边的是徐加的结束  mt
                                if let str = (data[2]["data"] as? [String:Any])?["val"] {
                                    var zeroFlag: Bool = false
                                    if str is String {
                                        zeroFlag = ((str as? String) == "0.00")
                                    }
                                    else {
                                        zeroFlag = ((str as? Int) == 0)
                                    }
                                    
                                    self.dismissLoadHUD()
                                    self._loadView = UIHelper.initLoadView(self, withMessage: "进入游戏...")
                                    self.parent?.view.addSubview(self._loadView!)

                                    self.pushGameViewController(dict!)
                                    
                                }else{
                                    
                                    UIHelper.alertSimpleMessage(about: "检查账户失败，请稍后重试。", withDescription: "", in: self)
                                    self._loadView?.removeFromSuperview()
                                    //mt20171221 添
                                    self._effecView?.removeFromSuperview()
                                }
                            }else {
                                //注册游戏
                                //                              [UIHelper displayTip:@"系统维护中，当前无法进入游戏" delay:1.5f view:self.view];
                                //checkREG(accid, url: url)
                                self.checkReg(dict!)
                            }
                        }
                        else {
                            
                            UIHelper.alertSimpleMessage(about: "系统维护中，当前无法进入游戏，在此期间建议您选择其它万博游戏平台娱乐", withDescription: "", in: self)
                        }
                        self.dismissLoadHUD()
                        //mt20171221 添
                        self._effecView?.removeFromSuperview()
                    }
                    else {
                        
                        let tip: String = "系统维护中(\(s["s"] as? String ?? "")-\(s["e"] as? String ?? ""))，当前无法进入游戏"
                        UIHelper.alertSimpleMessage(about: tip, withDescription: "", in: self)
                        self.dismissLoadHUD()
                        //mt20171221 添
                        self._effecView?.removeFromSuperview()
                    }
                }
                else if code == 999 || code == 1150 {
                    UIHelper.displayLoginExpireTip(self)
                    //mt20171221 添
                    UIHelper.removeEffect()
                }
                else {
                    ToolHelper.statisticsPage(pageName:"\(self.selectedRecommendGameTitle)-\(dict?["name"] as? String ?? "")-api_失败")
                    UIHelper.alertSimpleMessage(about: "发生错误: \(Int(code))", withDescription: "", in: self)
                    self.dismissLoadHUD()
                    //mt20171221 添
                    self._effecView?.removeFromSuperview()
                }
            }
            
        }, withError: { error in
            print(error)
            DispatchQueue.main.async {
                ToolHelper.statisticsPage(pageName:"\(self.selectedRecommendGameTitle)-\(dict?["name"] as? String ?? "")-api_失败")
                UIHelper.alertSimpleMessage(about: "检查账户失败，请稍后重试，\(getErrorString())。", withDescription: "", in: self)
                self.dismissLoadHUD()
                //mt20171221 添
                self._effecView?.removeFromSuperview()
            }
        })
    }
    
    func pushGameViewController(_ gp: [String:Any]){
        self._loadView?.removeFromSuperview()
        if let games = gp["games"] as? [[String:Any]] {
            //Platforms with sub games
            let vc = VideoGamesVC()
            vc.platform = gp
            vc.subGameList = games
            vc.hidesBottomBarWhenPushed=true
            self.navigationController?.pushViewController(vc, animated: true)
            
        }else{
            if let useWK = gp["use_WK"] as? Bool {
                if useWK == false {
                    let goNext: GameWebViewController = GameWebViewController.instanceFromStoryboard()!
                    goNext.gpid = gp["gpid"] as? String
                    goNext.url = gp["url"] as? String
                    goNext.hidesBottomBarWhenPushed = true
                    self.navigationController?.pushViewController(goNext, animated: true)
                    
                }else{
                    
                    let goNext = GameWKWebViewController.instanceFromStoryboard()!
                        
                    goNext.gpid = gp["gpid"] as? String
                    goNext.url = gp["url"] as? String
                    goNext.hidesBottomBarWhenPushed = true
                    self.navigationController?.pushViewController(goNext, animated: true)
                }
            }
        }
    }
    
    func checkReg(_ platform: [String:Any]){
        let gpid = platform["accid"] as? String
        DispatchQueue.main.async {
            self.dismissLoadHUD()
            self._loadView = UIHelper.initLoadView(self, withMessage: "检查账号...")
            self.parent?.view.addSubview(self._loadView!)
        }
        
        RequestHelper.post(atPath: "/kz/gp/reg", withData: ["gpid":gpid!], withCompletion: { data in
            let responseObject = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
            let code = responseObject["c"] as! Int
            print("reg:\(responseObject)")
            DispatchQueue.main.async {
                if code == 0 {
                    //进入游戏
                    self.pushGameViewController(platform)
                }
                else if code == 1407 {
                    //mt 20171221 add
                    self._effecView?.removeFromSuperview()
                    UIHelper.alertSimpleMessage(about: "系统维护中，当前无法进入游戏，在此期间建议您选择其它万博游戏平台娱乐。", withDescription: "", in: self)
                }
                else if code  == 999 || code  == 1150 {
                    //mt 20171221 add
                    self._effecView?.removeFromSuperview()
                    UIHelper.displayLoginExpireTip(self.parent!)
                }else{
                    
                }
                self.dismissLoadHUD()
                //mt 20171221 add
                self._effecView?.removeFromSuperview()
            }
            
        }, withError: { error in
            print(error)
            DispatchQueue.main.async {
                UIHelper.alertSimpleMessage(about: "系统维护中，当前无法进入游戏，在此期间建议您选择其它万博游戏平台娱乐。\(getErrorString())", withDescription: "", in: self)
            }
            self.dismissLoadHUD()
            //mt 20171221 add
            self._effecView?.removeFromSuperview()
        })
    }
}
